package com.example.teesystem.common.websocket;

import com.example.teesystem.common.exception.Assert;
import com.example.teesystem.common.utils.ResultCode;
import com.example.teesystem.controller.PKController;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 利用拦截器监听 websocket 连接
 */
@Component
public class PKInterceptor implements ChannelInterceptor {
    /**
     * 监听连接请求（从请求头里获取 uid 并将其放入到 sessions 中）
     * @param message
     * @param channel
     * @return
     */
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            Object nativeHeaders = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            if(nativeHeaders instanceof Map) {
                // 从请求头里获取 uid
                Integer uid = Integer.parseInt(((Map<String, List<String>>) nativeHeaders).get("uid").get(0));
                Assert.notNull(ResultCode.PARAMETER_MISS, uid);
                // 更新 sessions
                PKController.sessions.put(accessor.getSessionId(), uid);
    
                PKController.printStatus();
            }
        }
        return ChannelInterceptor.super.preSend(message, channel);
    }
    
//    /**
//     * 监听断开连接
//     * @param message
//     * @param channel
//     * @param sent
//     * @param ex
//     */
//    @Override
//    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
//        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
//        if(StompCommand.DISCONNECT.equals(accessor.getCommand())) {
//            System.out.println("DISCONNECT");
//
//            // 1. 从 sessions 里根据 sessionId 获取 uid
//            String sessionId = accessor.getSessionId();
//            Integer uid = PKController.sessions.get(sessionId);
//
//            // 2. 更新 userInfos 和 groupInfos
//            PKController.userInfos.remove(uid);
//            PKController.sessions.remove(sessionId);
//
//            System.out.println("有用户断开连接，断开的用户为：" + uid);
//            System.out.println("------- 现有用户 --------");
//            PKController.userInfos.values().stream().forEach(System.out::println);
//            System.out.println("---------------");
//        }
//    }
}
